package center;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2020-07-16
 * Time: 14:28
 *
 * @author zyh
 */
public class WatcherCallback implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {

    ZooKeeper zooKeeper;
    private String path;
    private CountDownLatch countDownLatch;
    private TestConfig testConfig;

    public WatcherCallback(ZooKeeper zooKeeper, String path, TestConfig testConfig) {
        this.zooKeeper = zooKeeper;
        this.path = path;

        this.testConfig = testConfig;
    }

    @Override
    public void process(WatchedEvent event) {
        Event.EventType type = event.getType();
        switch (type) {
            case None:
                break;
            case NodeCreated:
                zooKeeper.getData(this.path, this, this, "getData");
                break;
            case NodeDeleted:
                testConfig.setIp(null);
                break;
            case NodeDataChanged:
                zooKeeper.getData(this.path, this, this, "getData");
                break;
            case NodeChildrenChanged:
                break;
            case DataWatchRemoved:
                break;
            case ChildWatchRemoved:
                break;
            default:
                break;
        }

    }

    /**
     * await
     */
    public void await() throws InterruptedException {
        this.countDownLatch = new CountDownLatch(1);
        this.zooKeeper.exists(path, this, this, "exists");
        this.countDownLatch.await();
    }

    /**
     * exists watcher
     *
     * @param rc
     * @param path
     * @param ctx
     * @param stat
     */
    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {

        System.out.println("defaultWatcher processResult");
        if (stat != null) {
            System.out.println("exists stat" + stat.getVersion());
            zooKeeper.getData(this.path, this, this, "getData");
        } else {
            System.out.println("exists stat is null ");
        }
    }

    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        if (stat == null) {
            System.out.println("getdata state is null");
        } else {
            System.out.println("getdata state is "+stat.getVersion());
            String dataStr = new String(data);
            testConfig.setIp(dataStr);
            this.countDownLatch.countDown();
        }

    }
}
